package com.chixing.controller;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.chixing.pojo.Car;
import com.chixing.pojo.MyCoupon;
import com.chixing.pojo.MyOrder;
import com.chixing.pojo.StoreCar;
import com.chixing.service.*;
import com.chixing.util.ServerResponse;
import com.chixing.util.alipay.AlipayConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author Wesley
 * @version 1.0
 * @date 2021/10/9 13:51
 */
@Controller
@RequestMapping("alipay")
public class AliPayController {
    final static Logger log = LoggerFactory.getLogger(AliPayController.class);
    @Autowired
    private CarService carService;
    @Autowired
    private MyOrderService myOrderService;
    @Autowired
    private FlowService flowService;
    @Autowired
    private StoreCarService storeCarService;
    @Autowired
    private MyCouponService myCouponService;
    @Autowired
    private RedisTemplate redisTemplate;
//
//    @GetMapping("getFlowById/{flowId}")
//    @ResponseBody
//    public ModelAndView getFlowById(@PathVariable("flowId") Integer flowId){
//        ServerResponse serverResponse = flowService.getById(flowId);
//        ModelAndView mav = new ModelAndView();
//        mav.addObject("",serverResponse);
//        mav.setViewName("");
//        return mav;
//    }

    // 1 . 支付：调用支付宝支付
    @RequestMapping(value = "/goAlipay", produces = "text/html; charset=UTF-8")
    @ResponseBody
    public String pay(Integer myOrderId, Float myOrderPrice, Integer carId,
                      Integer myOrderLeaseDays,Integer custId){
        Car car = carService.getById(carId);

        System.out.println("调用支付宝沙箱");

        // (1)初始化alipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json", AlipayConfig.charset,
                AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

        //(2)设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl("http://localhost:8080/xj_car_rental/alipay/alipayReturnNotice");
//        alipayRequest.setReturnUrl(AlipayConfig.return_url);
//        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        Integer out_trade_no = myOrderId;
        Float total_amount = myOrderPrice;
        String subject = car.getCarName();
        String body = custId.toString();
        System.out.println("out_trade_no:" + out_trade_no);
        System.out.println("total_amount:" + total_amount);
        System.out.println("subject:" + subject);
        System.out.println("body:" + body);


        // (3)支付请求中的订单信息，
        String timeout_express = "5m";
        alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
                + "\"total_amount\":\""+ total_amount +"\","
                + "\"subject\":\""+ subject +"\","
                + "\"body\":\""+ body +"\","
                + "\"timeout_express\":\""+ timeout_express +"\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        String result = null;
        try {
            result = alipayClient.pageExecute(alipayRequest).getBody();
            System.out.println("result :"+result);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        return result;
    }

    // 2 . 新增flow流水记录 + 修改订单信息

    //支付后的获得支付宝的信息
    @RequestMapping(value = "/alipayReturnNotice")
    public String alipayReturnNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {
        log.info("pay successfully ,支付成功, 进入同步通知接口...");
        System.out.println("支付成功后，支付宝返回的所有的数据："+ request);
        //获取支付宝GET过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            System.out.println("return notice name:"+name);
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        System.out.println("params:"+params);
        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
        System.out.println("return notice signVerified:"+signVerified);
        ModelAndView mv = new ModelAndView("alipaySuccess");
        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
            System.out.println("return out_trade_no:"+out_trade_no);//订单编号
            System.out.println("return trade_no:"+trade_no);//流水号
            System.out.println("return total_amount:"+total_amount);//流水金额
            //新增流水记录
            Integer myOrderId = Integer.valueOf(out_trade_no);
            MyOrder myOrder = (MyOrder) myOrderService.getById(myOrderId).getData();
            System.out.println(myOrder);
                    //利用UUID生成订单号
        String[] chars = new String[] {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
        StringBuffer shortBuffer = new StringBuffer();
        String uuid = UUID.randomUUID().toString().replace("-","");
        for (int j=0;j<16;j++) {
            String str=uuid.substring(j*2,j*2+2);
            int par=Integer.parseInt(str,24);
            shortBuffer.append(chars[par % 10]);
        }
        Long flowNumber = Long.valueOf(shortBuffer.toString());
            Integer custId = myOrder.getCustId();
            Float payAmount = Float.valueOf(total_amount);
//            myOrderService.updateOrderStatus2(myOrder);
            myOrder.setStatus(2);

            Integer storeId = myOrder.getStoreBorrowId();
            Integer carId = myOrder.getCarId();
            String redisStoreCarKey2 = storeId+"storeCarUpdate"+carId;
            String redisStoreCarKey = storeId+"-storeCar-"+carId;
            StoreCar storeCar = (StoreCar) storeCarService.getStoreCarByStoreIdAndCarId(storeId, carId).getData();
            //车辆库存减一
            storeCar.setCarReserve(storeCar.getCarReserve() - 1);
            //车辆销量加一
            storeCar.setCarSaleCount(storeCar.getCarSaleCount() + 1);
            if(redisTemplate.hasKey(redisStoreCarKey)){
                redisTemplate.opsForValue().set(redisStoreCarKey2,"",10,TimeUnit.SECONDS);
                redisTemplate.opsForValue().set(redisStoreCarKey,storeCar,10,TimeUnit.MINUTES);
            }
            else
                storeCarService.updateStoreCar(storeCar);
            //优惠券失效
            Integer couponId = myOrder.getCouponId();
            MyCoupon myCoupon = myCouponService.getByConditions(custId, couponId);
            if(myCoupon != null){
                myCouponService.updateStatus1(myCoupon);
            }
            Car car = (Car)carService.getCarDetail(myOrder.getCarId()).getData();
            log.info("********************** 支付成功(支付宝同步通知) **********************");
            log.info("* 订单号: {}", out_trade_no);
            log.info("* 支付宝交易号: {}", trade_no);
            log.info("* 实付金额: {}", total_amount);
            log.info("* 购买产品: {}", car.getCarName());
            log.info("***************************************************************");
            myOrderService.firstPush(myOrder);
            String redisMyOrderKey = "myOrderId_" + myOrderId;
            String redisKey = "myOrderNum_" + myOrderId;
            redisTemplate.opsForValue().set(redisMyOrderKey,myOrder);
            redisTemplate.opsForValue().set(redisKey,"",1000,TimeUnit.MILLISECONDS);
            flowService.save(flowNumber, custId, myOrderId, payAmount);
//            mv.addObject("flow",flow);
//            mv.setViewName("order/six_receipt_number");
            return "redirect:/flow/" + flowNumber;

        }else {
            log.info("支付, 验签失败...");
            return "redirect:/";
        }
    }



    @RequestMapping(value = "/alipayNotifyNotice")
    @ResponseBody
    public String alipayNotifyNotice(HttpServletRequest request, HttpServletRequest response) throws Exception {

        log.info("支付成功, 进入异步通知接口...");

        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//			valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——

		/* 实际验证过程建议商户务必添加以下校验：
		1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
		2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
		3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
		4、验证app_id是否为该商户本身。
		*/
        if(signVerified) {//验证成功
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //交易状态
            String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意： 尚自习的订单没有退款功能, 这个条件判断是进不来的, 所以此处不必写代码
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知

                // 修改叮当状态，改为 支付成功，已付款; 同时新增支付流水
//                orderService.updateOrderStatus(out_trade_no, trade_no, total_amount);

                MyOrder order = (MyOrder) myOrderService.getById(Integer.valueOf(out_trade_no)).getData();

                Car car = (Car)carService.getCarDetail(order.getCarId()).getData();

                log.info("********************** 支付成功(支付宝异步通知) **********************");
                log.info("* 订单号: {}", out_trade_no);
                log.info("* 支付宝交易号: {}", trade_no);
                log.info("* 实付金额: {}", total_amount);
                log.info("* 购买产品: {}", car.getCarName());
                log.info("***************************************************************");
            }
            log.info("支付成功...");

        }else {//验证失败
            log.info("支付, 验签失败...");
        }

        return "success";
    }
}
